﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf.Message;
using Room;
namespace UI
{
    public class MiniMapComponent : MonoBehaviour
    {
        public UITexture map;
        private string mapImageName;
        public UIWidget frame;
        public GameObject offsetAnthor;
        protected Dictionary<string, GameObject> dictNpc = new Dictionary<string, GameObject>();
        protected Dictionary<string, GameObject> dictIcon = new Dictionary<string, GameObject>();
        protected Dictionary<string, Transform> dictCharactor = new Dictionary<string, Transform>();

        public float scalePosition = 4;
        public Vector2 offsetPosition;
        public float angle;

        public GameObject player;

        public GameObject otherTemplete;
        public GameObject npcTemplate;

        public Transform charactors;
        [HideInInspector]
        public Transform major;

        //小图描点
        public Transform small;
        public Room.RoomBase room;
        public GameObject unionFightOrder;
        public GameObject gatherPoint;
        bool isHaveGather;
        public void Init(float angle, Room.RoomBase room)
        {
            this.angle = angle;
            this.room = room;
            SetViewZoneSize();
            //whitePanel = GameObject.Find("/UI Root/WhitePanel");
            SwitchSmall();
        }

        public void SetUnionFightOrderShow(bool value)
        {
            unionFightOrder.SetActive(value);
        }

        public void SetGatherPoint(bool isShow, Vector3 pos = new Vector3())
        {
            isHaveGather = isShow;
            gatherPoint.SetActive(isShow);
            if(isShow)
                gatherPoint.transform.localPosition = GetTransPosition(pos);
        }
        bool flag = true;
        void SetPointShow()
        {
            if (isHaveGather)
            {
                var pos = offsetAnthor.transform.parent.InverseTransformPoint(gatherPoint.transform.position);
                bool isShow = !(pos.x < -75 || pos.x > 75 || pos.y < -56 || pos.y > 56);
                if(isShow != flag)
                {
                    gatherPoint.SetActive(isShow);
                    flag = isShow;
                }
            }
        }

        public void SetData(string mapImage, float offsetX, float offsetY, float angle, float scale)
        {
            if (!string.IsNullOrEmpty(mapImageName) && mapImageName != mapImage)
            {
                AssetLoadHelper.Instance.UnloadBundle("miniMap/" + mapImageName);
            }
            if(mapImage != mapImageName)
            {
                AssetLoadHelper.Instance.SetTextureAsync(map, "miniMap/" + mapImage, true);
                mapImageName = mapImage;
            }
            //map.MakePixelPerfect();
            scalePosition = scale;
            offsetPosition = new Vector2(offsetX, offsetY);
            this.angle = angle;
            SetViewZoneSize();
        }

        public void UnloadResource()
        {
            if (!string.IsNullOrEmpty(mapImageName))
            {
                AssetLoadHelper.Instance.UnloadBundle("miniMap/" + mapImageName);
                mapImageName = null;
                map.mainTexture = null;
            }
        }

        public void SetData(string mapImage)
        {
            if (!string.IsNullOrEmpty(mapImageName) && mapImageName != mapImage)
            {
                AssetLoadHelper.Instance.UnloadBundle("miniMap/" + mapImageName);
            }
            if (mapImage != mapImageName)
            {
                AssetLoadHelper.Instance.SetTextureAsync(map, "miniMap/" + mapImage, true);
                mapImageName = mapImage;
            }
        }


        private void SetViewZoneSize()
        {
            charactors.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, angle));
            map.transform.localPosition = new Vector3(offsetPosition.x * scalePosition, offsetPosition.y * scalePosition, 0);
        }

        public virtual void LoadFixedCharactor(string guid, Room.RoomCharactor npc)
        {
            if (dictNpc.ContainsKey(guid))
            {
                GameObject.Destroy(dictNpc[guid]);
                dictNpc.Remove(guid);
            }
            if (string.IsNullOrEmpty(npc.extraInfo))
            {
                return;
            }
            GameObject inst = GameObject.Instantiate(npcTemplate);
            inst.transform.SetParent(offsetAnthor.transform);
            inst.SetActive(true);
            UISprite sp = inst.GetComponent<UISprite>();
            sp.spriteName = npc.extraInfo;
            sp.MakePixelPerfect();
            inst.transform.localPosition = GetTransPosition(npc.transform.localPosition);
            inst.name = guid;
            inst.transform.localScale = Vector3.one;

            dictNpc[guid] = inst;
        }

        void SCCurrentPosition(object obj)
        {
            SCCurrentPosition pos = (SCCurrentPosition)obj;

            var sceneName = pos.self.position.scene;
            if (sceneName == ServerScene.Town)
            {
                ManagerController.Instance.LoginToUI();
            }
            else
            {
                ManagerController.Instance.LoginToField(sceneName);
            }
        }

        public Vector3 GetTransPosition(Vector3 worldPosition)
        {
            Vector3 p = worldPosition;
            p.x = worldPosition.x * scalePosition;
            p.y = worldPosition.z * scalePosition;
            p.z = 0;
            return p;
        }
        
        public virtual void LoadLiveCharactor(string guid, Room.RoomCharactor rc)
        {
            if (dictCharactor.ContainsKey(guid))
            {
                Destroy(dictCharactor[guid]);
                dictCharactor.Remove(guid);
            }
            bool shouldCreate = false;
            string spName = null;
            switch (rc.type)
            {
                case Room.CharactorType.Box:
                    shouldCreate = true;
                    spName = "UI_ditu_baoxiang";
                    break;
                case CharactorType.UnionFightChariot:
                case Room.CharactorType.Monster:
                    shouldCreate = true;
                    if (rc.extraInfo == "1")
                    {
                        spName = "UI_ditu_boss";
                    }
                    else
                    {
                        spName = "UI_zhujiemian_ditu_06";
                    }
                    break;
                case CharactorType.UnionFightMonster:
                    shouldCreate = true;
                    spName = "UI_ditu_boss";
                    break;
                case CharactorType.UnionFightGuard:
                case CharactorType.UnionFightOther:
                case Room.CharactorType.OtherPlayer :
                    shouldCreate = true;
                    if (rc.extraInfo == "red")
                    {
                        spName = "UI_ditu_hongming";
                    }
                    else
                    {
                        spName = "UI_zhujiemian_ditu_03";
                    }
                    break;

                case Room.CharactorType.Fish:
                    shouldCreate = true;
                    spName = "UI_ditu_yugou";
                    break;
                case CharactorType.UnionFightMine:
                case CharactorType.Mine:
                    shouldCreate = true;
                    spName = "UI_ditu_wakuang";
                    break;
                case CharactorType.ServerMonster:
                    shouldCreate = true;
                    spName = "UI_zhujiemian_ditu_06";
                    break;
                case CharactorType.FieldBoss:
                case CharactorType.UnionFightBoss:
                    shouldCreate = true;
                    spName = "UI_ditu_boss";
                    break;
                    //case Room.CharactorType.AirWall:
                    //    shouldCreate = false;
                    //    spName = "UI_ditu_aiengelangte";
                    //    break;

            }
            if (!shouldCreate)
            {
                return;
            }

            dictCharactor[guid] = rc.transform;

            GameObject inst = GameObject.Instantiate(otherTemplete);
            inst.SetActive(true);
            UISprite sp = inst.GetComponent<UISprite>();

            sp.spriteName = spName;
            sp.MakePixelPerfect();
            inst.transform.SetParent(offsetAnthor.transform);
            inst.transform.localScale = Vector3.one;
            inst.name = guid;
            dictIcon[guid] = inst;
        }

        //public void OnCharactorDestory(Room.RoomCharactor ch)
        //{
        //    UnloadLiveCharactor(ch.name);
        //}

        public virtual void UnloadCharactor(string guid)
        {
            if (dictCharactor.ContainsKey(guid))
            {
                dictCharactor.Remove(guid);
                GameObject.Destroy(dictIcon[guid]);
                dictIcon.Remove(guid);
            }
            else if (dictNpc.ContainsKey(guid))
            {
                Destroy(dictNpc[guid]);
                dictNpc.Remove(guid);
            }
            else
            {
                //Debug.Log("mini map not exist charactor " + guid);
            }
        }

        /// <summary>
        /// 设置主角
        /// </summary>
        /// <param name="tran"></param>
        public virtual void SetMajorCharactor(Transform tran)
        {
            this.major = tran;
        }


        void Update()
        {
            //同步主角
            if (major != null)
            {
                var z = major.transform.localRotation.eulerAngles.y + 90;
                player.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, z));
                Vector3 p = major.transform.localPosition;
                p.y = 0;
                p = p * scalePosition;
                offsetAnthor.transform.localPosition = new Vector3(-p.x, -p.z, 0);
            }

            // 同步其他玩家
            if (dictCharactor.Count > 0)
            {
                foreach (var kvp in dictCharactor)
                {
                    var key = kvp.Key;
                    var tran = kvp.Value;
                    

                    var var0 = tran.GetComponent<RoomCharactor>();
                    if (var0 != null && var0.type == CharactorType.OtherPlayer)
                    {
                        //红名
                        var var1 = "";
                        var killerNum = var0.ai.GetKillNum();
                        var killer = Dict.Blo.DictKillerBlo.GetKillerData(killerNum);
                        if (killer.jailFlag == 1)
                        {
                            var1 = "UI_ditu_hongming";
                        }
                        else
                        {

                            if (!string.IsNullOrEmpty(StaticData.playerData.teamId) && StaticData.playerData.team != null)
                            {
                                var pid = var0.name;
                                var isTeam = false;
                                foreach (var member in StaticData.playerData.team.memberList)
                                {
                                    if (member.playerId == long.Parse(pid))
                                    {
                                        isTeam = true;
                                        break;
                                    }
                                }

                                if(isTeam)
                                    var1 = "UI_zhujiemian_ditu_08";
                                else
                                    var1 = "UI_zhujiemian_ditu_03";
                            }
                            else
                            {
                                var1 = "UI_zhujiemian_ditu_03";
                            }
                        }

                        if(dictIcon[key].GetComponent<UISprite>().spriteName!= var1)
                        {
                            dictIcon[key].GetComponent<UISprite>().spriteName = var1;
                            dictIcon[key].GetComponent<UISprite>().MakePixelPerfect();
                        }
                    }
                    dictIcon[key].transform.localPosition = GetTransPosition(tran.localPosition);
                }
            }

            //集合点
            SetPointShow();
        }

        public virtual void OnClick()
        {
            var s = Room.RoomManager.currentRoom.name;
            if (s == "TOWN")
            {
                PageManager.instance.OpenPage("TownMapPage", "");
            }
            else if(RoomManager.curSceneType == SceneType.UNIONFIGHT)
            {
                UIUnionFightRunMap.GetNetData().netBattle.OpenBigMap();
            }
        }

        public void SwitchSmall()
        {
            map.gameObject.SetActive(true);
            small.gameObject.SetActive(true);
        }

        public void SwitchToSmall()
        {
            map.transform.SetParent(offsetAnthor.transform);
            map.gameObject.SetActive(false);
            offsetPosition = new Vector2(7.0675f, 12.35f);
            SetData("UI_zhujiemian_ditu_512", offsetPosition.x, offsetPosition.y, 0f, 4f);
            map.gameObject.SetActive(true);

            small.gameObject.SetActive(true);
        }

        private static MiniMapComponent instance = null;

        public static MiniMapComponent Instance
        {
            get
            {
                if(instance == null)
                {
                    var temp = Resources.Load<GameObject>("prefab/MiniMap");
                    var inst = GameObject.Instantiate(temp);
                    var parent = RoomUIManager.Instance.transform;
                    inst.SetActive(true);
                    inst.transform.SetParent(parent);
                    inst.transform.localPosition = new Vector3(473, 240, 0);
                    inst.transform.localScale = Vector3.one;
                    inst.transform.localRotation = Quaternion.Euler(Vector3.zero);
                    instance = inst.GetComponent<MiniMapComponent>();
                }
                return instance;
            }
        }

    }
}